package com.example.support.wanquanpay;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.Duration;
import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSON;
import com.shitu.api.ClientConfig;
import com.shitu.api.DefaultSdkClient;
import com.shitu.api.ResponseVO;
import com.shitu.api.SdkClient;
import com.shitu.api.constants.AcctChangeType;
import com.shitu.api.constants.AcctQueryType;
import com.shitu.api.constants.BusType;
import com.shitu.api.model.OpenAcctModel;
import com.shitu.api.model.OrderPayModel;
import com.shitu.api.model.PayInfoDetail;
import com.shitu.api.model.QueryAcctModel;
import com.shitu.api.model.RegisterModel;
import com.shitu.api.model.UpdateAcctModel;
import com.shitu.api.request.AbstractFlexibleRequest;
import com.shitu.api.request.OpenAcctRequest;
import com.shitu.api.request.OrderPayRequest;
import com.shitu.api.request.OrderQueryRequest;
import com.shitu.api.request.QueryAcctInfoRequest;
import com.shitu.api.request.QueryAcctRequest;
import com.shitu.api.request.RegisterRequest;
import com.shitu.api.request.SubOrderQueryRequest;
import com.shitu.api.request.UpdateAcctRequest;
import com.shitu.api.response.AbstractApiResponse;
import com.shitu.api.response.OrderPayResponse;
import com.shitu.api.response.OrderQueryResponse;
import com.shitu.api.response.QueryAcctInfoResponse;
import com.shitu.api.response.QueryAcctResponse;
import com.shitu.api.response.RegisterResponse;
import com.shitu.api.response.SubOrderQueryResponse;
import com.shitu.api.response.UpdateAcctResponse;
import com.shitu.api.response.OrderPayResponse.FailOrderDetail;
import com.example.foo.account.AccountHelper;
import com.example.foo.wanquanpay.service.WanquanPayLogService;
import com.example.support.redis.RedisHelper;

@org.springframework.stereotype.Component
public class WanquanPay {

	private final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(getClass());

	//支付通道（1:众邦 2:支付宝）
	protected static final String payPass_bank = "1";
	protected static final String payPass_alipay = "2";

	private static final String MERCHANT_NO = "A10079-B10208-M10925";
	private static final String PROVIDER_NO = "S10086";
	private static final String PRODUCT_NO = "P1413409427";
	private static final String TASK_CODE = "S140742200523";
	private static final String PRIVATE_KEY = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCT/n/VLb45VvXnCMuC7Vpj4oz7W1Ub48Zzs9pRA3MWtLoDHnm0iGpZji6eRdPrwY5rTCmHXDg5B45KvgwFKWGxtaF9APqGxXeOiHJ4Cp5o41ZZxsNmgoOBc3cSyGglYGGKBLcGDDfUp5b6uJ8q+WuPqrMc2axd0YkqPwzRjJZ8g3T7DzyUZ0gdYrwlVHIzNgpMhjSggVYnMnZwuKvKyFoz0qbpIqPO0uG175XoOXtLzR2J3PMy8Vsc3938aiosq/IYqhwNJBchmQdQyHxodEsecsfyBi58UQ+QabMqimRCR2WYbpf8ReifbHj+jO1YDIseA4I/hLaL8n0fPgl9cUX/AgMBAAECggEAURrMW7vx3+K0aKT9Qwdo3gyuTqJDBkHR5F7Qak2FqQ/qUQNGl5WbEvFEwyBpf25X6p2WtMPpW/e0F2oHlFyVWZq8oZEDuxBE8Sv976OCJOFR1WmEdI1aHHt26ihCSxmC2uyykPHpNvWRXF4JfLesJtPZzRnNyKyoiyp6j+yIHDvpap+1c0sqmN+7ZSuuJ1bINyF+CnEPi3FgBgNgRRralVR2s9igajeD/SpCsGRM3P0mnd0yBRKAkHNmegSeQPAKYzE7w/8jm+4bcWxTQgMcB3wRABxUx8eSiKFPZAg+FZ+1Rf81dSuiNnrom3CL177jmOo/7QBvmsAqzg5WfJXCQQKBgQDEES3Yeee49NplsM2RsYP1pJlaCcgNYt0vpjXWRcO8uXDoNcOelOoN1V6VG/g1MHn9K0cw9UomMk8Bef9G4eC7krTeh+vyziV3fXpgF2nQyFRGoAYRek2P29F9yQQ7/sTdK/3C8C2NUqi96BVrLEYiKZrCs6bKEy9uMfm5NpUDiQKBgQDBO3iG83Zdfe9RQn8nwzUI5VNe9zYXU0fSui22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B";

	private final ClientConfig clientConfig;
	private final SdkClient sdkClient;
	private final WanquanPayLogService wanquanPayLogService;

	public WanquanPay(WanquanPayLogService wanquanPayLogService) {
		ClientConfig clientConfig = new ClientConfig(MERCHANT_NO, PROVIDER_NO, PRODUCT_NO, TASK_CODE, PRIVATE_KEY, SYSTEM_PUBLIC_KEY);
		SdkClient sdkClient = new DefaultSdkClient(clientConfig);
		this.clientConfig = clientConfig;
		this.sdkClient = sdkClient;
		this.wanquanPayLogService = wanquanPayLogService;
	}

	/**
	 * 注册会员
	 */
	private String registerMember(RegisterModel registerModel) {
		RegisterModel bizModel = RegisterModel.Builder.builder()
				.phone(registerModel.getPhone())
				.providerNo(clientConfig.getProviderNo())
				.name(registerModel.getName())
				.idCard(registerModel.getIdCard())
				.busType(BusType.ENTRUSTED_COLLECTED.getType())
				.build();
		RegisterRequest request = new RegisterRequest(bizModel);
		request.setFrontImg(new File(registerModel.getImgIdCardFront()));
		request.setBgImg(new File(registerModel.getImgIdCardBack()));
		RegisterResponse response = callApi(request);
		return response.getMemberId();
	}

	/**
	 * 注册会员
	 */
	public String registerMember(String idCard, String name, String phone, File imgIdCardFront, File imgIdCardBack) {
		RegisterModel registerModel = new RegisterModel();
		registerModel.setIdCard(idCard);
		registerModel.setName(name);
		registerModel.setPhone(phone);
		registerModel.setImgIdCardFront(imgIdCardFront.getAbsolutePath());
		registerModel.setImgIdCardBack(imgIdCardBack.getAbsolutePath());
		return registerMember(registerModel);
	}

	/**
	 * 变更会员
	 */
	private UpdateAcctResponse updateMember(UpdateAcctModel updateAcctModel) {
		UpdateAcctModel bizModel = UpdateAcctModel
				.Builder
				.builder()
				.providerNo(clientConfig.getProviderNo())
				.busType(updateAcctModel.getBusType())
				.phone(updateAcctModel.getPhone())
				.payPass(updateAcctModel.getPayPass())
				.bankNo(updateAcctModel.getBankNo())
				.cardNo(updateAcctModel.getCardNo())
				.bankPhone(updateAcctModel.getBankPhone())
				.merchantNo(clientConfig.getMerchantNo())
				.changeType(updateAcctModel.getChangeType())
				.memberId(updateAcctModel.getMemberId())
				.build();
		UpdateAcctRequest request = new UpdateAcctRequest(bizModel);
		if (updateAcctModel.getImgIdCardFront() != null) {
			request.setIdCardFrontImg(new File(updateAcctModel.getImgIdCardFront()));
		}
		if (updateAcctModel.getImgIdCardBack() != null) {
			request.setIdCardBackImg(new File(updateAcctModel.getImgIdCardBack()));
		}
		return callApi(request);
	}

	/**
	 * 变更会员影像件
	 */
	public void updateMemberImagePiece(String memberId, String phone, File imgIdCardFront, File imgIdCardBack) {
		UpdateAcctModel updateAcctModel = new UpdateAcctModel();
		updateAcctModel.setChangeType(AcctChangeType.CHG_IMAGE_PIECE.getChangeType());
		updateAcctModel.setMemberId(memberId);
		updateAcctModel.setPhone(phone);
		updateAcctModel.setImgIdCardFront(imgIdCardFront.getAbsolutePath());
		updateAcctModel.setImgIdCardBack(imgIdCardBack.getAbsolutePath());
		updateMember(updateAcctModel);
	}

	/**
	 * 变更会员结算卡
	 */
	public void updateMemberBank(String memberId, String phone, String bankNo, String cardNo, String bankPhone) {
		UpdateAcctModel updateAcctModel = new UpdateAcctModel();
		updateAcctModel.setChangeType(AcctChangeType.CHG_CARD_INFO.getChangeType());
		updateAcctModel.setMemberId(memberId);
		updateAcctModel.setPhone(phone);
		updateAcctModel.setPayPass(WanquanPay.payPass_alipay);
		updateAcctModel.setBankNo(bankNo);
		updateAcctModel.setCardNo(cardNo);
		updateAcctModel.setBankPhone(bankPhone);
		updateMember(updateAcctModel);
	}

	/**
	 * 转账
	 */
	private OrderPayResponse orderPay(OrderPayModel orderPayModel) {
		OrderPayModel bizModel = OrderPayModel.Builder
				.builder()
				.busType(BusType.INDIVIDUAL_REGISTRATION.getType())
				.batchNumber(batchNumber0())
				.merchantNo(clientConfig.getMerchantNo())
				.productCode(clientConfig.getProductNo())
				.taskCode(clientConfig.getTaskCode())
				.providerNo(clientConfig.getProviderNo())
				.payPass(orderPayModel.getPayPass())
				.costUndertaker("1")//手续费承担方 1:企业承担 2:客户承担
				.payList(orderPayModel.getPayList())
				.build();
		OrderPayRequest request = new OrderPayRequest(bizModel);
		return callApi(request);
	}

	/**
	 * 转账
	 */
	public OrderPayResponse orderPayBank(String memberId, String idCard, String name, String fee) {
		PayInfoDetail payInfoDetail = new PayInfoDetail();
		payInfoDetail.setMemberId(memberId);
		payInfoDetail.setIdCard(idCard);
		payInfoDetail.setName(name);
		payInfoDetail.setFee(fee);

		OrderPayModel orderPayModel = new OrderPayModel();
		orderPayModel.setPayPass(WanquanPay.payPass_alipay);
		orderPayModel.setPayList(Arrays.asList(payInfoDetail));
		return orderPay(orderPayModel);
	}

	/**
	 * 开通银行账户
	 */
	public void openAcct(OpenAcctModel openAcctModel, HttpServletRequest httpServletRequest) {
		OpenAcctModel bizModel = OpenAcctModel.Builder.builder()
				.providerNo(clientConfig.getProviderNo())
				.payPass(WanquanPay.payPass_alipay)
				.memberId(openAcctModel.getMemberId())
				.bankNo(openAcctModel.getBankNo())
				.cardNo(openAcctModel.getCardNo())
				.bankPhone(openAcctModel.getBankPhone())
				.ipAdr(getIpAddr(httpServletRequest))
				.validDateStart(openAcctModel.getValidDateStart())
				.validDateEnd(openAcctModel.getValidDateEnd())
				.address(openAcctModel.getAddress())
				.build();
		OpenAcctRequest request = new OpenAcctRequest(bizModel);
		request.setImgFace(new File(openAcctModel.getImgFace()));
		callApi(request);
	}

	/**
	 * 查询会员
	 */
	private QueryAcctResponse queryAcct(QueryAcctModel queryAcctModel) {
		QueryAcctModel bizModel = new QueryAcctModel();
		bizModel.setType(queryAcctModel.getType());
		bizModel.setPayPass(queryAcctModel.getPayPass());
		bizModel.setMemberId(queryAcctModel.getMemberId());
		bizModel.setIdCard(queryAcctModel.getIdCard());

		log.info("bizModel:      "+bizModel);
		log.info("bizModel:  getType    "+bizModel.getType());
		log.info("bizModel:  getPayPass    "+bizModel.getPayPass());
		log.info("bizModel:  getMemberId    "+bizModel.getMemberId());
		log.info("bizModel:  getIdCard    "+bizModel.getIdCard());
		QueryAcctRequest request = new QueryAcctRequest(bizModel);
		return callApi(request);
	}

	/**
	 * 查询会员基本信息
	 */
	public QueryAcctResponse queryMemberBaseByMemberId(String memberId) {
		QueryAcctModel queryAcctModel = new QueryAcctModel();
		queryAcctModel.setType(AcctQueryType.QRY_BASIC_INFO.getType());
		queryAcctModel.setMemberId(memberId);
		QueryAcctResponse response = queryAcct(queryAcctModel);
		return response;
	}

	/**
	 * 查询会员开户信息
	 */
	public QueryMemberAcctStatusResponse queryMemberAcctStatusByMemberId(String memberId) {
		QueryAcctModel queryAcctModel = new QueryAcctModel();
		queryAcctModel.setType(AcctQueryType.QRY_OPEN_ACCT_INFO.getType());
		queryAcctModel.setPayPass(WanquanPay.payPass_alipay);
		queryAcctModel.setMemberId(memberId);
		QueryAcctResponse response = queryAcct(queryAcctModel);
		return new QueryMemberAcctStatusResponse(response.getAcctStatus(), response.getMsg());
	}

	/**
	 * 查询会员ID
	 */
	public String queryMemberIdByIdCard(String idCard) {
		QueryAcctModel bizModel = new QueryAcctModel();
		bizModel.setType(AcctQueryType.QRY_MEMBER_ID.getType());
		bizModel.setIdCard(idCard);
		QueryAcctResponse response = queryAcct(bizModel);
		return response.getMemberId();
	}

	/**
	 * 查询商户
	 */
	public QueryAcctInfoResponse queryMerchant() {
		QueryAcctInfoRequest request = new QueryAcctInfoRequest(WanquanPay.payPass_alipay);
		return callApi(request);
	}

	/**
	 * 查询订单
	 */
	public OrderQueryResponse queryOrderByBatchOrderNo(String batchOrderNo) {
		OrderQueryRequest request = new OrderQueryRequest(batchOrderNo);
		return callApi(request);
	}

	/**
	 * 查询子订单
	 */
	public SubOrderQueryResponse querySubOrderByOrderNo(String orderNo) {
		SubOrderQueryRequest request = new SubOrderQueryRequest(orderNo);
		return callApi(request);
	}

	private <R extends AbstractApiResponse> R callApi(AbstractFlexibleRequest<R> request) throws WanquanPayException {
		ResponseVO<R> response;
		try {
			response = sdkClient.execute(request);
		} catch (Exception e) {
			log.error("请求失败", e);
			throw new WanquanPayException("请求失败", e);
		}

		if (!response.getSuccess()) {
			throw new WanquanPayException("响应失败: " + response.getMessage());
		}

		String api = request.getApi();
		String statusCode = response.getResult().getStatusCode();
		String msg = response.getResult().getMsg();

		String json = JSON.toJSONString(request) + "/" + JSON.toJSONString(response);
		log.info(json);
		wanquanPayLogService.createWanquanPayLog(api, statusCode, msg, json);

		if (statusCode.equals("1002")) {
			String stack = msg;
			if (response.getResult() instanceof OrderPayResponse) {
				OrderPayResponse orderPayResponse = (OrderPayResponse) response.getResult();
				if (orderPayResponse.getFailList() != null) {
					List<String> remarks = orderPayResponse.getFailList()
							.stream()
							.map(FailOrderDetail::getRemark)
							.collect(Collectors.toList());
					stack = msg + "; " + String.join("; ", remarks);
				}
			}
			log.error(stack);
			throw new WanquanPayException(stack);
		}

		return response.getResult();
	}

	private String batchNumber0() {
		// 当天日期+五位序列号 20200101-00001
		Integer periodDay = AccountHelper.toPeriodDay(LocalDate.now());
		String key = String.format("wanquanpay:batchNumber_%s", periodDay);
		Long val = RedisHelper.incr(key);
		if (val == 1) {
			RedisHelper.expire(key, Duration.ofHours(25).getSeconds());
		}
		return periodDay + "-" + StringUtils.leftPad(val.toString(), 5, '0');
	}

    /**
     * 获取用户实际ip
     * @param request
     * @return
     */
    @Deprecated//TODO remove
    private String getIpAddr(HttpServletRequest request){
        String ipAddress = request.getHeader("x-forwarded-for");
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
            if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
                //根据网卡取本机配置的IP
                InetAddress inet=null;
                try {
                    inet = InetAddress.getLocalHost();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                ipAddress= inet.getHostAddress();
            }
        }
        //对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
        if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
            if(ipAddress.indexOf(",")>0){
                ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
            }
        }
        return ipAddress;
    }

}
